"""
开发规范
在此文件中写的你需要完成的函数即可
返回值必须为字典 键分别为 code msg result
code为响应代码
msg为请求信息
result则是前端需要的结果，按前端的需求返回


code代码
成功 200
缺少参数 1001
参数错误 1002
其他问题 1003
目前想到的就这点 如果你发现了新的问题记得补充并通知大家
msg信息
成功 ok
不成功 error
result结果
这段返回前端所需要的结果
例如 前端需要一个用户的昵称 返回格式为 {‘name’:昵称}
在一切正常的情况下你的返回结果应该是
data = {
    'code':200,
    'msg':'ok',
    'result':{'name':'查到的昵称（根据需求而定）'}
}

"""
import re
import sys
import json
from api import models
from api import querys
from qiniu import Auth, put_data, etag
from django.db.models import Q
import qiniu.config

querys_module = sys.modules[querys.__name__]


def test(request):

    data = {
        'code':200,
        'msg':'ok',
        'result':'123'
    }
    if request.method == 'GET':
        # 获取get请求中的fun参数的值
        fun = request.GET.get('fun')
        #获取get请求中的name参数的值
        name = request.GET.get('name')
    else:
        # 获取get请求中的fun参数的值
        fun = request.POST.get('fun')
        # 获取get请求中的name参数的值
        name = request.POST.get('name')
    # print('name',name)
    data['result'] = name
    return data
#登录账户
def login(request):
    data = {
        'code': 200,
        'msg': 'error',
        'result': '未知错误'
    }
    username = request.POST.get('username')
    password = request.POST.get('password')
    obj = models.User.objects.filter(username=username).values('username', 'password')
    if len(obj) == 0:
        print("没有这个用户")
        data['result'] = '没有这个用户'
    else:
        if password != obj[0]['password']:
            data['msg'] = 'error'
            data['result'] = '密码错误'
        else:
            data['msg'] = 'ok'
            data['result'] = '登录成功'
    return data


#注册账号
def register(request):
    data = {
        'code': 200,
        'msg': 'error',
        'result': 'success'
    }
    fun = request.POST.get('fun')
    if fun == 'register':
        username = request.POST.get('username')
        password = request.POST.get('password')
        nickname = request.POST.get('nickname')
        email = request.POST.get('email')
        print(username,password,nickname,email)
        if username == None or not username.isalnum():
            data['result'] = '账号格式不正确'
            data['code'] = 1002
            print('账号')
            return data
        if password == None or not password.isalnum():
            data['result'] = '密码格式不正确'
            data['code'] = 1002
            print('密码')
            return data
        if nickname == None:
            data['result'] = '请填写昵称'
            data['code'] = 1002
            print('昵称')
            return data
        if email ==None or  re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) == None:
            data['result'] = '请填写正确的电子邮件'
            data['code'] = 1002
            print('邮箱')
            return data

        obj = models.User.objects.filter(username=username)
        if obj :
            data['result'] = '已存在的用户'
            data['code'] = 1003
            return data
        else:
            user_obj = models.User.objects.create(
                username=username,
                password=password,
                nickname=nickname,
                email=email,
            )
            print('创建')

            if user_obj.username:
                data['msg'] = 'ok'
                data['result'] = '%s创建成功'%username
                print(user_obj)
                return data
        data['result'] = '未知错误'
        data['code'] = 1003
        return data

# 用户发表动态
def publication_dynamics(request):
    data = {
        'code': 200,
        'msg': 'error',
        'result': 'success'
    }
    username = request.POST.get('username')
    user_obj = models.User.objects.filter(username=username).first()
    print(user_obj)
    if user_obj == None:
        data['code'] = 1003
        data['result'] = '没有此用户'
        return data
    if username == None:
        data['result'] = '没有用户名'
        data['code'] = 1001
        return data
    if user_obj :
        context = request.POST.get('context')
        if context == None:
            data['code'] = 1001
            data['result'] = '内容不能为空！'
            return data
        obj = models.Dynamic.objects.create(
            launch_user=user_obj,
            context=context
        )
        print('obj',obj.add_date)
        data['msg'] = 'ok'
        data['result'] = '发表成功'
        return data

#关注相关操作
def attention(request):
    data = {
        'code': 1001,
        'msg': 'error',
        'result': '没有传入用户id'
    }
    username = request.POST.get("username")
    if username == None:
        return data
    user = models.User.objects.filter(username=username).first()
    other = request.POST.get("attention")
    if other != None:
        obj = models.User.objects.filter(username=other).first()
        #此时将关注其他人
        if obj != None:
            print('obj',obj)
            #判断是否已经关注过此人
            flag = models.Attention.objects.filter(username=user,attention_user=obj).first()
            #如果找到这个记录，说明需要删除这个记录
            if flag != None:
                models.Attention.objects.filter(username=user, attention_user=obj).delete()
                data['code'] = 200
                data['msg'] = 'ok'
                data['result'] = '取消关注成功'
            else:
                creat = models.Attention.objects.create(username = user,attention_user=obj)
                data['code'] = 200
                data['msg'] = 'ok'
                data['result'] = '关注成功'
    else:
        data['code'] = 1001
        data['msg'] = 'error'
        data['result'] = '请传入另外一个人的id'
    return data
#加入项目相关操作
def attention_project(request):
    data = {
        'code': 1001,
        'msg': 'error',
        'result': '请检查传入的参数'
    }
    username = request.POST.get("username")
    if username == None:
        data['result'] = '请传入用户名'
        return data
    #实例化user对象
    user = models.User.objects.filter(username=username).first()
    project_id = request.POST.get('projectId')
    if project_id!=None and project_id.isdigit():
        project_id = int(project_id)
        #实例化项目对象
        project = models.Projects.objects.filter(id=project_id)
        if project:
            project = project.first()
        else:
            data['result'] = '活动不存在'
            return data
        obj = models.Join_project.objects.filter(username=user,project_id=project)
        print(obj)
        if obj:
            data['code'] = 200
            data['msg'] = 'ok'
            data['result'] = '你已经加入过了'
        else:
            creat = models.Join_project.objects.create(username=user,project_id=project)
            data['code'] = 200
            data['msg'] = 'ok'
            data['result'] = '加入成功'

    return data
# 查询相关
def query(request):
    #可以执行的查询动作【动态，资料，关注,收藏，未结束活动，加入的社团,排行榜，关注用户，项目加入人数】
    query_list = ['dynamics','self_data','attention','favorite','query_project','communitied','leaderboard','attention_dynamics','join_project']
    query_type = request.POST.get('query_type')
    if query_type in query_list:
        username = request.POST.get('username')
        query = getattr(querys_module,query_type)(username,request)
        return query
    else:
        data = {'code': 1003,'msg': 'error','result': '没有这个查询模块'}
        return data

# 修改个人资料(目前只允许修改昵称)
def changhe(request):
    username = request.POST.get("username")
    change = request.POST.get("information")
    data = {
        'code': 1002,
        'msg': 'error',
        'result': '参数传入错误'
    }
    if username != None and change != None:
        change = json.loads(change)
        change_obj = models.User.objects.filter(username=username).update(nickname=change['nickname'])
        print(change_obj,type(change_obj))
        if change_obj:
            data['code'] = 200
            data['msg'] = 'ok'
            data['result'] = '修改成功'
        else:
            data['code'] = 1003
            data['msg'] = 'error'
            data['result'] = '没有此用户'
        return data
    else:
        return data


# 积分商城物品信息展示
def integral_goods(request):
    data = {
        'code': 1001,
        'msg': 'error',
        'result':"success"
    }
    date=models.Shop.objects.all()
    date_list=[]
    for row in date:
        date_list.append({"id":row.id,"desc":row.desc,"img":row.img,"value":row.value,"add_date":row.add_date,"mod_date":row.mod_date})
    if date_list!=None:
        print("数据获取成功")
        data['msg']="ok"
        data['result']=date_list
        data['code']=200
    else:
        data['result']="查询结果为空"
    return data



#积分商城购买物品
def buy_goods(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }

    username = request.GET.get("username")
    good_id=request.GET.get("id")

    a=models.Shop.objects.filter(id=good_id)
    b=models.User.objects.filter(username=username)
    if a.count()!=0 and b.count()!=0:
        #获取商品价钱
        goods_obj=models.Shop.objects.filter(id=good_id).first()
        goods_value=goods_obj.value

        #获取公益积分
        user_obj=models.User.objects.filter(username=username).first()
        user_integral=user_obj.integral


        if user_integral>=goods_value:
            data['code']=200
            data['msg']="ok"
            print("兑换成功")

            #修改公益积分
            models.User.objects.filter(username=username).update(integral=user_integral-goods_value)

            #改变产品属于
            models.Shop.objects.filter(id=good_id).update(username=models.User.objects.get(username=username))

            data['result']={'goods_master':username,"now_integral":user_integral-goods_value}

        else:
            data['result']="公益积分不足"
    else:
        data['result'] = "商品不存在或用户名不存在"
    return data


#用户上传图片接口
def user_upload_img(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    # 获取图片对象
    image_file = request.FILES.get("img")

    Img = True
    # 图片不为空上传七牛云
    try:
        # 获取对象二进制
        image_data = image_file.read()
    except Exception:
        Img = False
    if Img:
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'ilzJNKLpKs2M2oCE6aeVFQc7RM_30xFw4iTsxR93'
        secret_key = 'IH0FnoSbn5kB1LFUsWuxsLBbkthMU1Qxks-Vo0_w'

        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'cccoder-img'
        # 上传后保存的文件名

        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, None, 3600)

        ret, info = put_data(token, None, image_data)

        small_img = "http://q5goyk5rs.bkt.clouddn.com/%s?imageView2/2/w/70/h/70" % ret['key']
        pur_img = "http://q5goyk5rs.bkt.clouddn.com/%s" % ret['key']
        date = {"small_img": small_img, "pur_img": pur_img}
        data['code'] = 200
        data['msg'] = "ok"
        data['result'] = date
        print(data)
    else:

        data['code'] = 1001
        data['result'] = "缺少参数"
        print(data)


    return data


#公益项目编辑标题
def edit_title(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取项目信息
    pro_id = request.POST.get("pro_id")
    Pro_id=models.Projects.objects.filter(id=pro_id).exists()
    #获取新标题
    new_title=request.POST.get("new_title")
    #获取用户信息
    user = request.POST.get("username")
    user1 = models.User.objects.filter(username=user).first()
    user_certification = int(user1.certification)
    #获取项目对应的社团信息
    community = models.Projects.objects.filter(id=pro_id).values("community")
    for i in community:
        print (i["community"])
        user_is_community=models.Join_community.objects.filter(community_id=i['community'],username=user).exists()
    if user_certification<1:
        data['result']="用户权限不够"
    elif Pro_id==False:
        data['result']="项目不存在"
    elif user_is_community==False:
        data['result']="用户没在此社团"
    elif user_certification>=1:
        models.Projects.objects.filter(id=int(pro_id)).update(title=new_title)
        data['code']=200
        data['msg']="ok"
    else:
        data['code']=1001
        data['result']="参数错误"

    return data



#公益项目编辑项目进度
def pro_speed(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取新进度
    Pro_speed=int(request.POST.get("new_speed"))

    #项目信息
    pro_id = request.POST.get("pro_id")
    Pro_id = models.Projects.objects.filter(id=pro_id).exists()

    #用户信息
    user = request.POST.get("username")
    user1 = models.User.objects.filter(username=user).first()
    user_certification = int(user1.certification)
    #获取项目对应的社团信息
    community = models.Projects.objects.filter(id=pro_id).values("community")
    for i in community:
        print (i["community"])
        user_is_community = models.Join_community.objects.filter(community_id=i['community'], username=user).exists()

    if user_certification<1:
        data['result']="用户权限不够"
    elif Pro_id==False:
        data['result']="项目不存在"
    elif user_is_community==False:
        data['result']="用户没在此社团"
    elif user_certification>=1:
        if Pro_speed<=5:
            models.Projects.objects.filter(id=int(pro_id)).update(progress=Pro_speed)
            if Pro_speed==5:
                models.Projects.objects.filter(id=int(pro_id)).update(finish=1)
                data['result']="pro_finish"
            data['code']=200
            data['msg']="ok"
    else:
        data['code']=1001
        data['result']="参数错误"

    return data


#公益项目留言和信息展示
def left_message(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }

    #获取留言人信息
    left_user=request.POST.get("left_user")
    user1 = models.User.objects.filter(username=left_user).first()
    user_certification = int(user1.certification)

    #获取留言的内容
    left_content=request.POST.get("left_content")

    #获取留言的项目id
    pro_id = request.POST.get("pro_id")
    Pro_id = models.Projects.objects.filter(id=pro_id).exists()

    #判断条件
    if user_certification<1:
        data['result']="用户权限不够"
    elif Pro_id==False:
        data['result']="没有此项目"
    elif left_content=="":
        data['result']="留言的内容为空"
    elif user_certification>=1:
        #数据存储
        models.Comments_projects.objects.create(project_id=models.Projects.objects.filter(id=pro_id).first(),commentator=models.User.objects.filter(username=left_user).first(),content=left_content)
        #数据返回

        ret_data = models.Comments_projects.objects.filter(project_id=pro_id).values("commentator","commentator__avatar","content", "add_date")
        date_list = []
        left_num = models.Comments_projects.objects.filter(project_id=pro_id).count()
        for i in ret_data:
            date_list.append({"left_num": left_num, "commentator": i["commentator"], "avatar": i["commentator__avatar"],
                              "content": i["content"], "add_date": i["add_date"]})

        data['result']=date_list
        data['code']=200
        data['msg']="ok"
    else:
        data['code'] = 1001
        data['result'] = "参数错误"
    return data


#创建社团
def create_association(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取创建人信息
    username=request.POST.get("create_people")
    user=models.User.objects.filter(username=username).first()
    user_certification=user.certification

    #获取社长信息
    president=request.POST.get("president")
    pre=models.User.objects.filter(username=president).first()
    president_certification=pre.certification

    #获取社团名
    name=request.POST.get("name")
    name_true=models.Community.objects.filter(name=name).exists()
    print (name_true)
    #获取社团头像
    avatar=request.POST.get("avatar")

    #进行级别判定
    if user_certification<2:
        data['result']="创建人认证级别不够"
    elif president_certification<2:
        data['result']="社长认证级别不够"
    elif name_true:
        data['result']="创建的社团名称已经存在了"
    elif user_certification>=2 and username!="" and president!="" and name!="" and avatar!="":
        st=models.Community.objects.create(username=user,president=pre,name=name,avatar=avatar)
        data['code']=200
        data['msg']="ok"
        data['result']={"id":st.id}
    else:
        data['result']="参数错误"
        data['code']=1001

    return data



#发起公益文章
def create_article(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取创建人
    create_people=request.POST.get("create_people")
    user = models.User.objects.filter(username=create_people).first()
    user_certification = user.certification
    #获取标题
    title=request.POST.get("title")
    #获取内容
    content=request.POST.get("content")
    #获取图片
    img=request.POST['img']
    img_list = list(img.split(","))
    #判断条件
    if user_certification<1:
        data['result']="创建人认证级别不够"
    elif content=="":
        data['result']="内容为空"
    elif title=="":
        data['result'] = "标题为空"
    elif user_certification>=1:
        a=models.Commonweal_article.objects.create(create_people=user,title=title,content=content)
        for i in img_list:
            if i!="":
               models.Article_img.objects.create(img=i,article_img=a)

        data['code'] = 200
        data['msg'] = "ok"
        data['result'] = {"id": a.id}
        print(img_list)
    else:
        data['result'] = "参数错误"
        data['code'] = 1001
    return data





#发起动态
def create_dynamic(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取项目目的
    objective=request.POST.get("objective")

    #判断条件
    if objective=="":
        data['result']="没有选择发起个人动态还是社团动态"
        #发布个人动态
    elif int(objective)==1:
        #获取用户
        user=request.POST.get("username")
        user1 = models.User.objects.filter(username=user).first()
        user_certification = int(user1.certification)
        #获取动态内容
        context=request.POST.get("context")
        #获取动态图片
        img=request.POST['img']
        img_list = list(img.split(","))

        if user_certification<1:
            data['result']="用户权限不够"
        elif context=="":
            data['result']="动态内容不能为空"
        elif user_certification>=1:
            a=models.Dynamic.objects.create(launch_user=user1,context=context)
            for i in img_list:
                if i != "":
                    models.Dynamic_img.objects.create(img=i, dynamic_img=a)
            data['code'] = 200
            data['msg'] = "ok"
            data['result'] = {"Dynamic_id": a.id}
            print(img_list)

        #发布社团动态
    elif int(objective)==2:

        #获取发布动态的社团id
        community_id=request.POST.get("community_id")
        community_true = models.Community.objects.filter(id=community_id).exists()



        #获取社团用户发起人
        user=request.POST.get("username")
        user1 = models.User.objects.filter(username=user).first()
        user_certification = int(user1.certification)


        #获取动态内容
        context=request.POST.get("context")

        #获取动态图片
        img=request.POST['img']
        img_list = list(img.split(","))

        if user_certification<1:
            data['result']="用户权限不够"
        elif community_id=="":
            data['result'] = "社团id为空"
        elif context=="":
            data['result']="动态内容为空"
        elif community_true==False:
            data['result']="没有该社团"
        elif user_certification>=1 and community_true:
            community_pro = models.Community.objects.filter(id=community_id).first()
            a=models.Community_dynamic.objects.create(launch_user=community_pro,context=context)
            for i in img_list:
                if i != "":
                    models.Community_dynamic_img.objects.create(img=i, community_img=a)
            data['code'] = 200
            data['msg'] = "ok"
            data['result'] = {"Community_dynamic_id": a.id}
            print(img_list)

    else:
        data['result'] = "参数错误"
        data['code'] = 1001
    return data




#公益项目创建和信息展示
def public_obj_show(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    # 获取创建人信息
    user = request.POST.get("username")
    user1 = models.User.objects.filter(username=user).first()
    user_certification = int(user1.certification)

    # 获取详情的信息
    details = request.POST.get('details')

    # 获取目的信息
    goal = request.POST.get('goal')

    # 获取项目名称
    pro_title = request.POST.get('title')

    # 获取项目背景图片
    background = request.POST.get('background')

    # 获取图片的信息
    details_img = request.POST["details_img"]
    details_img_list = list(details_img.split(","))
    purpose_img = request.POST['purpose_img']
    purpose_img_list = list(purpose_img.split(","))

    # 获取社团id信息
    community = request.POST.get('community_id')
    community_id = models.Community.objects.filter(id=community).exists()
    print (community_id)

    if user_certification < 2:
        data['result'] = "用户权限不够"
    elif community_id==False:
        data['result']="社团不存在"
    elif details == "":
        data['result'] = "详情信息为空"
    elif goal == "":
        data['result'] = "目的信息为空"
    elif background=="":
        data['result'] = "背景图片为空"
    elif user_certification >= 2:

        # 信息入库

        #获取社团对象
        community_obj = models.Community.objects.filter(id=community).first()
        #项目存入数据库
        pro_obj = models.Projects.objects.create(community=community_obj, details=details, purpose=goal,
                                                 title=pro_title, progress=1)
        #添加图片
        for i in details_img_list:
            models.Projects_img.objects.create(details_img=i, project_id=pro_obj)

        for j in purpose_img_list:
            models.Projects_img.objects.create(purpose_img=j, project_id=pro_obj)
        models.Projects_img.objects.create(background=background, project_id=pro_obj)


        print ('信息入库成功')

        # 信息返回
        new_num = models.Join_project.objects.filter(project_id=pro_obj.id).count()
        #查询项目信息
        info = models.Projects.objects.filter(pk=pro_obj.id).values("id", "community__name", "title","num", "details","purpose", "progress", "finish")
        pro_info = {"pro_id": info[0]["id"], "community_name": info[0]["community__name"], "title": info[0]["title"],"goal_num":info[0]['num'],"new_num":new_num,
                    "details": info[0]["details"],
                    "purpose": info[0]["purpose"], "progress": info[0]["progress"], "finish": info[0]["finish"]}

        #查询图片信息
        img_info = models.Projects_img.objects.filter(project_id=pro_obj.id).values("details_img", "purpose_img","background")
        details_img_lis = []
        purpose_img_lis = []
        for i in img_info:
            if i['details_img'] != "":
                details_img_lis.append(i['details_img'])
            if i["purpose_img"] != "":
                purpose_img_lis.append(i["purpose_img"])
            if i["background"] != "":
                pro_info['background'] = i["background"]
        pro_info['details_img'] = details_img_lis
        pro_info["purpose_img"] = purpose_img_lis
        data['result'] = pro_info
        data['code'] = 200
        data['msg'] = "ok"
        print('信息返回成功')


    else:
        data['code'] = 1001
        data['result'] = "缺少参数"
    return data


#搜索
def search(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    #获取标题
    context=request.POST.get("context")

    #判断条件
    if context=="":
        data['result']=""
    elif context!="":
        #判断是否存在
        a=models.Projects.objects.filter(title__icontains=context).exists()
        b=models.Commonweal_article.objects.filter(title__icontains=context).exists()
        list1 = []
        if a:
            #数据返回
            a1=models.Projects.objects.filter(title__icontains=context).values("id","title")
            for i in a1:
                list1.append({"type":"project","id":i['id'],"title":i['title']})
            data['code']=200
            data['msg']="ok"
        if b:
            #数据返回
            b1=models.Commonweal_article.objects.filter(title__icontains=context).values("id","title")
            for i in b1:
                list1.append({"type": "article", "id": i['id'], "title": i['title']})
            data['code'] = 200
            data['msg'] = "ok"

        data['result']=list1

    else:
        data['result']='数据为空'
    return data


#搜索之后点击信息展示
def search_onclick(request):
    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }
    onclick_type=request.POST.get("onclick_type")

    if onclick_type=="":
        data['result']="类型为空"
    elif onclick_type=="project":
        #获取项目id
        project_id=request.POST.get("project_id")
        project_true=models.Projects.objects.filter(id=project_id).exists()

        if project_true==False:
            data['result']="项目id不存在"
        #查找数据
        elif project_true:
            # 查询项目信息
            new_num = models.Join_project.objects.filter(project_id=project_id).count()
            info = models.Projects.objects.filter(pk=project_id).values("id", "community__name", "title","num", "details","purpose", "progress", "finish")
            pro_info = {"pro_id": info[0]["id"], "community_name": info[0]["community__name"],"title": info[0]["title"],"goal_num":info[0]['num'],"new_num":new_num,"details": info[0]["details"],"purpose": info[0]["purpose"], "progress": info[0]["progress"], "finish": info[0]["finish"]}

            # 查询留言信息
            ret_data = models.Comments_projects.objects.filter(project_id=project_id).values("commentator","commentator__avatar","content", "add_date")
            left_num = models.Comments_projects.objects.filter(project_id=project_id).count()
            date_list = []
            for i in ret_data:
                date_list.append(
                    {"left_num": left_num, "commentator": i["commentator"], "avatar": i["commentator__avatar"],
                     "content": i["content"], "add_date": i["add_date"]})

            # 查询图片信息
            img_info = models.Projects_img.objects.filter(project_id=project_id).values("details_img", "purpose_img","background")
            details_img_lis = []
            purpose_img_lis = []
            for i in img_info:
                if i['details_img'] != "":
                    details_img_lis.append(i['details_img'])
                if i["purpose_img"] != "":
                    purpose_img_lis.append(i["purpose_img"])
                if i["background"] != "":
                    pro_info['background'] = i["background"]
            pro_info['details_img'] = details_img_lis
            pro_info["purpose_img"] = purpose_img_lis

            pro_info['left_content']=date_list
            data['result'] = pro_info
            data['code'] = 200
            data['msg'] = "ok"
            print('信息返回成功')
    elif onclick_type=="article":
        #获取公益文章id
        article_id=request.POST.get("article_id")
        article_true=models.Commonweal_article.objects.filter(id=article_id).exists()

        if article_true==False:
            data['result']="公益文章不存在"

        elif article_true:
            #获取内容
            article_info=models.Commonweal_article.objects.filter(id=article_id).values("id","create_people","title","content","add_date")
            info = {"article_id": article_info[0]["id"],"create_people":article_info[0]["create_people"],"title":article_info[0]["title"],"content":article_info[0]["content"],"add_date":article_info[0]["add_date"]}
            #获取图片
            img_list=[]
            img_info=models.Article_img.objects.filter(article_img=article_id).values("img")
            for i in img_info:
                if i['img'] != "":
                    img_list.append(i["img"])
            info['img']=img_list
            data['result'] = info
            data['code'] = 200
            data['msg'] = "ok"
            print('信息返回成功')
    else:
        data['result']="输入的类型不对"
    return data



#主页优质公益活动展示
def good_project(request):

    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }

    date = models.Projects.objects.filter(finish=1)
    date_list = []
    for row in date:
        img_info = models.Projects_img.objects.filter(project_id=row.id)
        new_num = models.Join_project.objects.filter(project_id=row.id).count()
        for i in img_info:
            img=i.background
        date_list.append({"id": row.id, "title": row.title, "goal_num": row.num,"new_num":new_num,"background":img})
    if date_list != None:
        print("数据获取成功")
        data['msg'] = "ok"
        data['result'] = date_list
        data['code'] = 200
    else:
        data['result'] = "查询结果为空"
    return data


#主页正在进行公益活动展示
def conduct_project(request):

    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }

    date = models.Projects.objects.filter(finish__lt=1)

    date_list = []
    for row in date:
        img_info = models.Projects_img.objects.filter(project_id=row.id)
        new_num=models.Join_project.objects.filter(project_id=row.id).count()
        for i in img_info:
            img=i.background
        date_list.append({"id": row.id, "title": row.title, "goal_num": row.num,"new_num":new_num,"background":img})
    if date_list != None:
        print("数据获取成功")
        data['msg'] = "ok"
        data['result'] = date_list
        data['code'] = 200
    else:
        data['result'] = "查询结果为空"
    return data


#主页点击活动
def action(request):

    data = {
        'code': 1003,
        'msg': 'error',
        'result': "success"
    }

    project_id = request.POST.get("project_id")
    project_true = models.Projects.objects.filter(id=project_id).exists()

    if id=="":
        data['result']="id为空"
    if project_true == False:
        data['result'] = "项目id不存在"
    # 查找数据
    elif project_true:
        new_num = models.Join_project.objects.filter(project_id=project_id).count()
        # 查询项目信息
        info = models.Projects.objects.filter(pk=project_id).values("id", "community__name", "title", "details",
                                                                    "purpose", "progress", "finish","num")
        pro_info = {"pro_id": info[0]["id"], "community_name": info[0]["community__name"], "title": info[0]["title"],
                    "details": info[0]["details"], "purpose": info[0]["purpose"], "progress": info[0]["progress"],
                    "finish": info[0]["finish"],"goal_num":info[0]['num'],"new_num":new_num}
        # 查询留言信息
        ret_data = models.Comments_projects.objects.filter(project_id=project_id).values("commentator",
                                                                                         "commentator__avatar",
                                                                                         "content", "add_date")
        left_num = models.Comments_projects.objects.filter(project_id=project_id).count()
        date_list=[]
        for i in ret_data:
            date_list.append({"left_num": left_num, "commentator": i["commentator"], "avatar": i["commentator__avatar"], "content": i["content"],"add_date": i["add_date"]})
        # 查询图片信息
        img_info = models.Projects_img.objects.filter(project_id=project_id).values("details_img", "purpose_img",
                                                                                    "background")
        details_img_lis = []
        purpose_img_lis = []
        for i in img_info:
            if i['details_img'] != "":
                details_img_lis.append(i['details_img'])
            if i["purpose_img"] != "":
                purpose_img_lis.append(i["purpose_img"])
            if i["background"] != "":
                pro_info['background'] = i["background"]
        pro_info['details_img'] = details_img_lis
        pro_info["purpose_img"] = purpose_img_lis

        pro_info['left_content'] = date_list
        data['result'] = pro_info
        data['code'] = 200
        data['msg'] = "ok"
        print('信息返回成功')
    else:
        data['result'] = "参数错误"
    return data
# 社团
# ① 获取：社团信息——精选社团（横） √ (已修改)
def association(request):
    data = {
        "code":200,
        "msg":"ok",
        "result":None
    }
    # 所有社团基本信息——>社团头像+社团名
    for obj in models.Community.objects.all().values("avatar","name"):
        data["result"] ={"avatar":obj["avatar"],
                         "name":obj["name"]}
    return data

# ② 获取：所有社团 √
def associations(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": []
    }
    # 获取：本人账号
    username = request.POST.get("username")
    # 获取：所有社团
    community_msg = models.Community.objects.all().values("avatar",                     # 社团头像
                                                          "name",                       # 社团名称
                                                          "username_id",                # 社团账号
                                                          "id"                          # 社团序号
                                                         )
    for i in range(0,len(community_msg)):
        # 获取：社团头像
        avatar = community_msg[i]["avatar"]
        # 获取：社团名称
        name = community_msg[i]["name"]
        # 获取：社团内容
        context = models.Community_dynamic.objects.filter(launch_user_id = community_msg[i]["id"]).values("context")[0]["context"]
        # 获取：社团图片
        img = models.Community_dynamic_img.objects.filter(community_img_id = community_msg[i]["id"]).values("img")[0]["img"]
        # 判断：社团关注
        try:
            if models.Join_community.objects.get(username_id = username, community_id_id = community_msg[i]["id"]):
               attention = True
        except:
            attention = False

        data["result"].append({"community_avatar":avatar,             # 社团头像
                               "community_name":name,                 # 社团名称
                               "community_context":context,           # 社团动态
                               "community_img":img,                   # 社团图片
                               "community_attention":attention})      # 社团关注
    return data

# 社团动态内容
# ① 社团信息 √
def association_dynamic(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": []
    }
    # 获取：当前社团
    community_now_id = request.POST.get("community_now_id")
    # 获取：用户账号
    username = request.POST.get("username")
    print(community_now_id)
    # 获取：当前社团
    community_msg = models.Community.objects.filter(username_id = community_now_id).values("avatar",                     # 社团头像
                                                                                           "name",                       # 社团名称
                                                                                           "username_id",                # 社团账号
                                                                                           "id"                          # 社团序号
                                                                                          )
    # 获取：社团头像
    avatar = community_msg[0]["avatar"]
    # 获取：社团名称
    name = community_msg[0]["name"]
    # 获取：社团时间
    time = models.Community_dynamic.objects.filter(launch_user_id=community_msg[0]["id"]).values("mod_date")[0]["mod_date"]
    # 获取：社团内容
    context = models.Community_dynamic.objects.filter(launch_user_id=community_msg[0]["id"]).values("context")[0]["context"]
    # 获取：社团图片
    img = models.Community_dynamic_img.objects.filter(community_img_id=community_msg[0]["id"]).values("img")[0]["img"]
    # 获取：社团喜欢
    like = models.Dynamic.objects.filter(launch_user_id = community_msg[0]["username_id"]).values("like")[0]["like"]
    # 判断：社团关注
    attention = None
    try:
        if models.Join_community.objects.get(username_id=username, community_id_id=community_msg[0]["id"]):
            attention = True
    except:
        attention = False

    data["result"].append({"community_avatar": avatar,              # 社团头像
                           "community_name": name,                  # 社团名称
                           "community_time":time,                   # 社团时间
                           "community_context": context,            # 社团动态
                           "community_img": img,                    # 社团图片
                           "community_like":like,                   # 社团喜欢
                           "community_attention": attention})       # 社团关注
    return data
# ② 留言展示
def association_remark(request):
    data = {"code":200,
            "msg":"ok",
            "result":None
            }
    # 当前账号
    sponsor = request.POST.get("sponsor")
    # 获取内容
    remark_msg = models.Comments_dynamic.objects.filter(sponsor_id = sponsor).values("content",
                                                                                     "commentator_id",
                                                                                     "mod_date")
    remark_avatar = []
    remark_nickname = []
    remark_time = []
    remark_context = []
    for obj in remark_msg:
        remark_avatar.append(models.User.objects.filter(username = obj["commentator_id"]).values("avatar")[0]["avatar"])
        remark_nickname.append(models.User.objects.filter(username = obj["commentator_id"]).values("nickname")[0]["nickname"])
        remark_context.append(obj["content"])
        remark_time.append(obj["mod_date"])
    data["result"] = {"remark_avatar":remark_avatar,
                      "remark_nickname":remark_nickname,
                      "remark_time":remark_time,
                      "remark_context":remark_context}
    return data




# ③ 发布留言 √
def association_remark_publish(request):
    data = {"coe":200,
            "msg":"ok",
            "result":None
            }
    # 获取：用户账号
    user_id = request.POST.get("username")
    # 获取：所属账号
    sponsor = request.POST.get("sponsor")
    # 获取：留言内容
    context = request.POST.get("context")
    # Comments_dynamic
    # 创建：用户留言
    if context == "":
        data["result"] = False      # 失败
    else:
        models.Comments_dynamic.objects.create(sponsor_id = sponsor,
                                                commentator_id = user_id,
                                                content = context
                                                )
        data["result"] = True       # 成功
    return data

# 社团更多
# ① 获取：社团信息 √
def association_more(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": []
    }
    data["result"] = list(models.Community.objects.all().values("name",         #社团名称
                                                           "username",          #社团创始人
                                                           "num",               #社团人数
                                                           "avatar"))           #社团头像
    return data

# ② 获取：查找信息 √
def search_association(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": None
    }
    # 获取：用户输入信息
    search_msg = request.POST.get("context")
    # 获取：模糊查询包含用户输入信息的社团信息
    association_msg= list(models.Community.objects.filter(name__contains=search_msg).values("name",     # 社团名称
                                                                                      "president_id",   # 社团社长
                                                                                      "num",            # 社团人数
                                                                                      "avatar"))        # 社团头像
    for i in range(0,len(association_msg)):
        association_msg[i]["president_id"] = models.User.objects.filter(username = association_msg[i]["president_id"]).values("nickname")[0]["nickname"]
    data["result"] = association_msg
    return data

# 点开头像后的：
# ① 社团信息 √
def association_active(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": None
    }
    data["result"] = list(models.Community.objects.filter(username_id = request.POST.get("username_id")).values("avatar",     #社团头像
                                                                                                                "name",       #社团名
                                                                                                                "num"         #社团人数
                                                                                                                ))
    return data
# ② 社团活动 √
def association_activies(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": []
    }
    # 获取：当前社团id
    community_id = request.POST.get("community_id")
    # 获取：社团所有项目
    projects_msg = models.Projects.objects.filter(community_id = community_id).values("id",
                                                                                      "title",
                                                                                      "finish",
                                                                                      "add_date",
                                                                                      "num")
    for obj in projects_msg:
        project_img = models.Projects_img.objects.filter(project_id_id = obj["id"]).values("background")[0]["background"]
        project_join_people = len(models.Join_project.objects.filter(project_id_id = obj["id"]).values("username_id"))
        data["result"].append({"project_title":obj["title"],                    # 项目名称
                               "project_bg":project_img,                        # 项目图片
                               "project_time":obj["add_date"],                  # 项目时间
                               "project_finish":obj["finish"],                  # 项目程度
                               "project_join_people":project_join_people,       # 参加人数
                               "project_people_num":obj["num"]                  # 目标人数
                               })

    return data
# ③ 社团动态
def association_messagies(request):
    data = {
        "code": 200,
        "msg": "ok",
        "result": []
    }
    # 获取：本人账号
    username = request.POST.get("username")
    # 获取：所有社团
    community_msg = models.Community.objects.all().values("avatar",         # 社团头像
                                                          "name",           # 社团名称
                                                          "username_id",    # 社团账号
                                                          "id"              # 社团序号
                                                          )
    for obj in community_msg:
        # 获取：社团头像
        avatar = obj["avatar"]
        # 获取：社团名称
        name = obj["name"]
        # 获取：社团内容
        context = models.Community_dynamic.objects.filter(launch_user_id=obj["id"]).values("context")[0]["context"]
        # 获取：社团图片
        img = models.Community_dynamic_img.objects.filter(community_img_id=obj["id"]).values("img")[0]["img"]
        # 判断：社团关注
        try:
            if models.Join_community.objects.get(username_id=username, community_id_id=obj["id"]):
                attention = True
        except:
            attention = False

        data["result"].append({"community_avatar": avatar,  # 社团头像
                               "community_name": name,  # 社团名称
                               "community_context": context,  # 社团动态
                               "community_img": img,  # 社团图片
                               "community_attention": attention})  # 社团关注

    return data

# 优质公益项目
# ① 基本信息 √
def good_projects(request):
    data = {
        "code":200,
        "msg":"ok",
        "result":None
    }
    # 获取：项目ID
    project_id = request.POST.get("project_id")

    # 获取：背景图片
    project_background = models.Projects_img.objects.filter(project_id_id = project_id).values("background")[0]["background"]
    # 获取：项目标题
    project_title = models.Projects.objects.filter(id = project_id).values("title")[0]["title"]
    # 获取：项目人数
    project_people_num = models.Projects.objects.filter(id = project_id).values("num")[0]["num"]
    # 获取：参与人数
    project_join_people = len(models.Join_project.objects.filter(project_id_id = project_id).values("username_id"))
    # 获取：发起社团
    project_community = models.Projects.objects.filter(id = project_id).values("num")[0]["num"]
    # 获取：详情文本
    project_details_msg = models.Projects.objects.filter(id = project_id).values("details")[0]["details"]
    # 获取：详情图片
    project_details_img = models.Projects_img.objects.filter(project_id_id = project_id).values("details_img")[0]["details_img"]
    # 获取：目的文本
    project_purpose_msg = models.Projects.objects.filter(id = project_id).values("purpose")[0]["purpose"]
    # 获取：目的图片
    project_purpose_img = models.Projects_img.objects.filter(project_id_id = project_id).values("purpose_img")[0]["purpose_img"]
    # 获取：项目进展
    project_progress = models.Projects.objects.filter(id = project_id).values("progress")[0]["progress"]

    data["result"] ={"project_background":project_background,               # 背景图片
                     "project_title":project_title,                         # 项目标题
                     "project_people_num":project_people_num,               # 目标人数
                     "project_join_people":project_join_people,             # 现有人数
                     "project_community":project_community,                 # 项目来源
                     "project_details_msg":project_details_msg,             # 详情文本
                     "project_details_img":project_details_img,             # 详情图片
                     "project_purpose_msg": project_purpose_msg,            # 目的文本
                     "project_purpose_img": project_purpose_img,            # 目的图片
                     "project_progress": project_progress                   # 项目进展
                     }


    return data
# ② 项目留言 √
def project_leave_message(request):
    data = {
        "code":200,
        "msg":"ok",
        "result":[]
    }
    # 获取：项目id
    project_id = request.POST.get("project_id")
    # 获取：留言信息
    message = models.Comments_projects.objects.filter(project_id_id = project_id).values("commentator_id",      # 留言账号
                                                                                         "content",             # 留言内容
                                                                                         "mod_date")            # 留言时间
    for obj in message:
        user_avatar = models.User.objects.filter(username = obj["commentator_id"]).values("avatar")[0]["avatar"]
        user_nickname = models.User.objects.filter(username = obj["commentator_id"]).values("nickname")[0]["nickname"]
        user_mod_date = obj["mod_date"]
        user_content = obj["content"]
        data["result"].append({"user_avatar":user_avatar,      #用户信息
                               "user_nickname":user_nickname, #留言信息
                               "user_mod_date": user_mod_date,
                               "user_content": user_content
                              })
    return data

# 优质公益项目更多 √
def good_project_more(request):
    data = {
        "coed":200,
        "msg":"ok",
        "result":[]
    }
    # 获取：社团所有项目
    projects_msg = models.Projects.objects.all().values("id",
                                                        "title",
                                                        "finish",
                                                        "add_date",
                                                        "num"
                                                        )
    for obj in projects_msg:
        project_img = models.Projects_img.objects.filter(project_id_id=obj["id"]).values("background")[0]["background"]
        project_join_people = len(models.Join_project.objects.filter(project_id_id=obj["id"]).values("username_id"))
        data["result"].append({"project_title": obj["title"],                   # 项目名称
                               "project_bg": project_img,                       # 项目图片
                               "project_time": obj["add_date"],                 # 项目时间
                               "project_finish": obj["finish"],                 # 项目程度
                               "project_join_people": project_join_people,      # 参加人数
                               "project_people_num": obj["num"]                 # 目标人数
                               })

    return data

# 社团成员 √
def association_member(request):
    data ={
        "code":200,
        "msg":"ok",
        "result":None
    }
    # 获取：当前社长
    president_id = request.POST.get("president_id")
    # 获取：当前社团
    president_nickname = str(models.User.objects.filter(username = president_id).values("nickname")[0]["nickname"])
    president_avatar = str(models.User.objects.filter(username = president_id).values("avatar")[0]["avatar"])
    # 获取：社团id
    community_id = models.Community.objects.filter(president_id = president_id).values("id")[0]["id"]
    # 获取：成员账号
    member_id = models.Join_community.objects.filter(Q(community_id_id = community_id)&~Q(username_id = president_id)).values("username_id")
    print(member_id)
    member_nickname = []
    member_avatar = []
    for obj in member_id:
        member_nickname.append(str(models.User.objects.filter(username = obj["username_id"]).values("nickname")[0]["nickname"]))
        member_avatar.append(str(models.User.objects.filter(Q(username = obj["username_id"])).values("avatar")[0]["avatar"]))

    data ["result"] = {"president_nickname":president_nickname,          # 社长名称
                      "president_avatar": president_avatar,             # 社长头像
                      "member_nickname":member_nickname,                # 成员名称
                      "member_avatar":member_avatar                     # 成员头像
                      }
    return data
